/*
 * Copyright (C) 2008 Universidade Federal de Campina Grande
 *  
 * This file is part of OurGrid. 
 *
 * OurGrid is free software: you can redistribute it and/or modify it under the
 * terms of the GNU Lesser General Public License as published by the Free 
 * Software Foundation, either version 3 of the License, or (at your option) 
 * any later version. 
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT 
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
 * for more details. 
 * 
 * You should have received a copy of the GNU Lesser General Public License 
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 * 
 */
package org.ourgrid.peer.business.controller;

import java.util.List;

import org.ourgrid.common.interfaces.RemoteWorkerProviderClient;
import org.ourgrid.common.interfaces.to.LocalWorkerState;
import org.ourgrid.common.internal.IResponseTO;
import org.ourgrid.common.internal.response.LoggerResponseTO;
import org.ourgrid.common.internal.response.ReleaseResponseTO;
import org.ourgrid.common.statistics.control.WorkerControl;
import org.ourgrid.peer.business.controller.messages.ConsumerMessages;
import org.ourgrid.peer.business.dao.PeerDAOFactory;
import org.ourgrid.peer.response.StopWorkingResponseTO;
import org.ourgrid.peer.to.AllocableWorker;
import org.ourgrid.peer.to.LocalAllocableWorker;
import org.ourgrid.peer.to.RemoteConsumer;
import org.ourgrid.reqtrace.Req;

import br.edu.ufcg.lsd.commune.container.servicemanager.ServiceManager;
import br.edu.ufcg.lsd.commune.identification.DeploymentID;

/**
 * Implement remote Peer actions when the {@link RemoteWorkerProviderClient} fails.
 */
public class RemoteWorkerProviderClientFailureController {

	private static RemoteWorkerProviderClientFailureController instance = null;

	public static RemoteWorkerProviderClientFailureController getInstance() {
		if (instance == null) {
			instance = new RemoteWorkerProviderClientFailureController();
		}
		return instance;
	}

	private RemoteWorkerProviderClientFailureController() {}

	public void doNotifyRecovery(ServiceManager serviceManager, RemoteWorkerProviderClient monitorable, DeploymentID rwpcDID) {}

	/**
	 * Notifies that the {@link RemoteWorkerProviderClient} has failed
	 * @param monitorable The {@link RemoteWorkerProviderClient} that has failed.
	 * @param rwpcID The DeploymentID of the {@link RemoteWorkerProviderClient} that has failed.
	 */
	@Req("REQ119")
	public void doNotifyFailure(List<IResponseTO> responses, String rwpcPublicKey, String rwpcAddress) {

		RemoteConsumer remoteConsumer = PeerDAOFactory.getInstance().getConsumerDAO().getRemoteConsumer(
				rwpcPublicKey);

		if (remoteConsumer == null) {

			LoggerResponseTO loggerResponse = new LoggerResponseTO(
					ConsumerMessages.getUnknownRemoteConsumerFailureMessage(rwpcAddress),
					LoggerResponseTO.DEBUG);

			responses.add(loggerResponse);
			return;
		}
		
		try {

			LoggerResponseTO loggerResponse = new LoggerResponseTO(
					ConsumerMessages.getRemoteConsumerFailureMessage(remoteConsumer.getConsumerAddress()),
					LoggerResponseTO.INFO);

			responses.add(loggerResponse);

			List<AllocableWorker> allocableWorkers = remoteConsumer.getAllocableWorkers();

			for (AllocableWorker allocableWorker : allocableWorkers) {

				allocableWorker.deallocate();

				WorkerControl.getInstance().statusChanged(responses,
						allocableWorker.getWorkerSpec().getUserAndServer(), 
						LocalWorkerState.IDLE);

				boolean workerIsUp = allocableWorker.getStatus().isUp();

				if (workerIsUp) {
					StopWorkingResponseTO stopWorkingResponse = new StopWorkingResponseTO();
					stopWorkingResponse.setWmAddress(allocableWorker.getWorkerAddress());
					responses.add(stopWorkingResponse);

				} else {

					WorkerNotificationController.workerFailure(responses, 
							((LocalAllocableWorker)allocableWorker).getLocalWorker());
				}


				if (allocableWorker.isDelivered()) {
					//Peer is already interested
					//				registerFailureInterested(workerMonitor, worker);
				}
			}

		} finally {
			ReleaseResponseTO releaseTO = new ReleaseResponseTO();
			releaseTO.setStubAddress(rwpcAddress);
			
			responses.add(releaseTO);
		}

	}

}